<?php

namespace app\admin\controller\system;

use app\admin\model\system\SystemAddons;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnotation;
use app\admin\model\system\SystemAddonsConfig;
use app\common\controller\AdminController;
use think\App;
use think\facade\Cache;

/**
 * @ControllerAnnotation(title="system_addons")
 */
class Addons extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\system\SystemAddons();

        $this->assign('select_list_admin', $this->model::SELECT_LIST_ADMIN, true);

        $this->assign('select_list_status', $this->model::SELECT_LIST_STATUS, true);
    }

    public function index()
    {
        $AddonsModel = new SystemAddons();

        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            //获取全部插件信息
            $result = $AddonsModel->getAllAddons();
            if ($result == '插件目录不可读或者不存在') {
                $this->error('插件目录不可读或者不存在');
            }
            $count = $result['count'];
            $list  = $result['list'];
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="配置管理")
     */
    public function manage(string $name)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            $config_data = [
                "config" => json_encode($post)
            ];
            try {
                $save = $this->model->where("name", $name)->update($config_data);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            // 生产模式，缓存数据
            if (!config('cache.develop_mode')) {
                Cache::tag('addons')->set('addons_config_' . $name, $post);
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $class_path = ROOT_PATH . 'addons/';
        if (is_file($class_path . $name . '/config.php')) {
            $config_file      = $class_path . $name . '/config.php';
            $config_file_data = include $config_file;
        }
        else {
            return "";
        }
        $data_config = json_decode($this->model->where("name", $name)->value('config'), true);
        foreach ($config_file_data as &$v) {
            $v["value"] = empty($data_config[$v["name"]]) ? "" : $data_config[$v["name"]];
        }
        $this->assign('config_file_data', $config_file_data);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="模板管理")
     */
    public function manage_field($id = 0)
    {
        if ($this->request->isAjax()) {
            $manage_field = (new \app\admin\model\system\SystemAddonsConfig)->where("addons_id", $id)->select()->toArray();
            $list         = [];
            if ($manage_field) {
                foreach ($manage_field as &$v) {
                    $config_name = $v["config_name"];  

                    $config       = json_decode($v["config"], true);
                    $config["id"] = $v["id"];
                    $config["config_name"] = $config_name;
                    $list[]       = $config;
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => count($list),
                'data'  => $list,
            ];
            return json($data);
        }

        $data_name  = $this->model->where("id", $id)->value('name');
        $class_name = "\addons\\{$data_name}\\{$data_name}";
        $res        = new $class_name();
        $info       = $res->admin["columns"];
        $columns    = [
            ["field" => 'config_name', "title" => '唯一标识'],
        ];
        foreach ($info as $v) {
            $column = [
                "field" => $v["name"],
                "title" => $v["title"],
            ];
            if ($v["name"] == "status") {
                $column["selectList"] = [1 => "启用", 0 => '禁用'];
            }
            $columns[] = $column;
        }

        $this->setDataBrage('columns', $columns);
        $this->setDataBrage('id', $id);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加字段")
     */
    public function manage_field_add($id = 0)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            $addons_name = SystemAddons::where("id",$id)->value("name");
            $configData = [
                "addons_id" => $id,
                "addons_name" => $addons_name,
                "config_name"=>$post["config_name"],
                "config"    => json_encode($post)
            ];
            try {
                $save = (new \app\admin\model\system\SystemAddonsConfig)->save($configData);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $data_name        = $this->model->where("id", $id)->value('name');
        $class_name       = "\addons\\{$data_name}\\{$data_name}";
        $res              = new $class_name();
        $config_file_data = $res->admin["columns"];
        $config_file_data []= ["name" => 'config_name', "type" => "text", "title" => '唯一标识',"tips"=>"配置的唯一标识，用来查询配置"];
        $this->assign('config_file_data', $config_file_data);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑配置")
     */
    public function manage_field_edit($id = 0)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            $configData = [
                "config_name"=>$post["config_name"],
                "config" => json_encode($post)
            ];
            try {
                $save = (new \app\admin\model\system\SystemAddonsConfig)->where("id", $id)->update($configData);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $addons           = SystemAddonsConfig::where("id", $id)->field("addons_id,config")->find();
        $data_name        = $this->model->where("id", $addons['addons_id'])->value('name');
        $class_name       = "\addons\\{$data_name}\\{$data_name}";
        $res              = new $class_name();
        $config_file_data = $res->admin["columns"];
        $config_file_data []= ["name" => 'config_name', "type" => "text", "title" => '唯一标识',"tips"=>"配置的唯一标识，用来查询配置"];
        $config_data      = json_decode($addons["config"], true);
        foreach ($config_file_data as &$v) {
            $v["value"] = empty($config_data[$v["name"]]) ? "" : $config_data[$v["name"]];
        }
        $this->assign('config_file_data', $config_file_data);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除配置")
     */
    public function manage_field_delete($id)
    {
        $this->checkPostRequest();
        $row = (new \app\admin\model\system\SystemAddonsConfig)->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = SystemAddonsConfig::whereIn('id', $id)->delete();
        } catch (\Exception $e) {
            $this->error('删除失败:' . $e->getMessage());
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * 安装插件
     * @NodeAnotation(title="安装插件")
     */
    public function install($name = '')
    {
        $addons_name = trim($name);
        if ($addons_name == '') {
            $this->error('插件不存在！');
        }
        $addons_class = get_addons_class($addons_name);
        if (!class_exists($addons_class)) {
            $this->error('插件文件不存在！');
        }

        // 实例化插件
        $addons = new $addons_class;

        // 插件预安装
        if (!$addons->install()) {
            $this->error('插件预安装失败!原因：' . $addons->getError());
        }
        // 插件配置信息
        $addons_info = $addons->info;
        // 并入插件配置值
        $addons_info['config'] = '';
        // 将插件信息写入数据库
        if (SystemAddons::create($addons_info)) {
            Cache::delete('addons_all');
            // 记录行为
            $this->success('插件安装成功');
        }
        else {
            $this->error('插件安装失败');
        }
    }

    /**
     * 卸载插件
     * @param string $name 插件标识
     * @NodeAnotation(title="卸载插件")
     * @Author jokerfei [ jokerfei377@gmail.com ]
     */
    public function uninstall(string $name = '')
    {
        $addons_name = trim($name);
        if ($addons_name == '') {
            $this->error('插件不存在！');
        }

        $class = get_addons_class($addons_name);
        if (!class_exists($class)) {
            $this->error('插件不存在！');
        }

        // 实例化插件
        $addons = new $class;
        // 插件预卸
        if (!$addons->uninstall()) {
            $this->error('插件预卸载失败!原因：' . $addons->getError());
        }
        // 删除插件信息
        $addonsInfo = (new \app\admin\model\system\SystemAddons)->where('name', $addons_name)->find();
        (new \app\admin\model\system\SystemAddonsConfig)->where('addons_id', $addonsInfo->id)->delete();
        if ($addonsInfo->delete()) {
            Cache::delete('addons_all');
            $this->success('插件卸载成功');
        }
        else {
            $this->error('插件卸载失败');
        }
    }

    /**
     * 启用插件
     * @param string $name 插件标识
     * @NodeAnotation(title="启用插件")
     * @Author jokerfei [ jokerfei377@gmail.com ]
     */
    public function enable(string $name = '')
    {
        SystemAddons::update(['status' => 1], ['name' => $name]);
        Cache::delete('addons_all');
        $this->success('插件启用成功');
    }

    /**
     * 禁用插件
     * @param string $name 插件标识
     * @NodeAnotation(title="禁用插件")
     * @Author jokerfei [ jokerfei377@gmail.com ]
     */
    public function disable(string $name = '')
    {
        SystemAddons::update(['status' => 0], ['name' => $name]);
        Cache::delete('addons_all');
        $this->success('插件禁用成功');
    }
}
